from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime, timedelta
import json
import requests
import hashlib
import time
from .models import WechatUser

# 微信登录配置
WECHAT_APP_ID = 'wxbf554b41c5f8f3d1'  # 替换为您的微信AppID
WECHAT_APP_SECRET = '6d3da06a05c2d209002567b8fb50338c'  # 替换为您的微信AppSecret

@csrf_exempt
def wechat_login(request):
    """
    微信登录接口
    支持两种方式：
    1. 通过code登录（小程序/网页授权）
    2. 直接使用openid登录（已获取过openid的情况）
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            login_type = data.get('type', 'code')  # 默认为code登录
            
            if login_type == 'code':
                # 通过code登录
                code = data.get('code')
                if not code:
                    return JsonResponse({
                        'status': 400,
                        'message': '缺少code参数'
                    }, status=400)
                
                # 请求微信接口获取openid和session_key
                url = f'https://api.weixin.qq.com/sns/jscode2session'
                params = {
                    'appid': WECHAT_APP_ID,
                    'secret': WECHAT_APP_SECRET,
                    'js_code': code,
                    'grant_type': 'authorization_code'
                }
                
                response = requests.get(url, params=params)
                result = response.json()
                
                if 'errcode' in result:
                    return JsonResponse({
                        'status': 400,
                        'message': f'微信登录失败：{result.get("errmsg")}'
                    }, status=400)
                
                openid = result.get('openid')
                session_key = result.get('session_key')
                
            else:
                # 直接使用openid登录
                openid = data.get('openid')
                if not openid:
                    return JsonResponse({
                        'status': 400,
                        'message': '缺少openid参数'
                    }, status=400)
                session_key = None
            
            # 生成用户token
            token = hashlib.md5(f"{openid}{time.time()}".encode()).hexdigest()
            
            # 获取或创建用户
            user, created = WechatUser.objects.get_or_create(
                openid=openid,
                defaults={
                    'nickname': '微信用户',
                    'avatar': 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
                    'gender': 0,
                    'token': token,
                    'token_expires_at': datetime.now() + timedelta(seconds=7200)
                }
            )
            
            # 如果是已存在的用户，更新token
            if not created:
                user.token = token
                user.token_expires_at = datetime.now() + timedelta(seconds=7200)
                user.save()
            
            return JsonResponse({
                'status': 200,
                'message': '登录成功',
                'data': {
                    'token': token,
                    'openid': openid,
                    'expires_in': 7200,  # token有效期，单位秒
                    'user_info': {
                        'nickname': user.nickname,
                        'avatar': user.avatar,
                        'gender': user.gender,
                        'country': user.country,
                        'province': user.province,
                        'city': user.city
                    }
                }
            })
            
        except json.JSONDecodeError:
            return JsonResponse({
                'status': 400,
                'message': '无效的JSON数据'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'status': 500,
                'message': f'登录失败：{str(e)}'
            }, status=500)
    else:
        return JsonResponse({
            'status': 405,
            'message': '仅支持POST请求'
        }, status=405)

@csrf_exempt
def wechat_user_info(request):
    """
    获取微信用户信息接口
    需要先登录获取token
    """
    if request.method == 'GET':
        try:
            # 获取token
            token = request.headers.get('Authorization')
            if not token:
                return JsonResponse({
                    'status': 401,
                    'message': '缺少token'
                }, status=401)
            
            # 获取用户信息
            try:
                user = WechatUser.objects.get(token=token)
            except WechatUser.DoesNotExist:
                return JsonResponse({
                    'status': 401,
                    'message': '无效的token'
                }, status=401)
            
            # 检查token是否过期
            if not user.is_token_valid():
                return JsonResponse({
                    'status': 401,
                    'message': 'token已过期'
                }, status=401)
            
            return JsonResponse({
                'status': 200,
                'data': {
                    'nickname': user.nickname,
                    'avatar': user.avatar,
                    'gender': user.gender,
                    'country': user.country,
                    'province': user.province,
                    'city': user.city
                }
            })
            
        except Exception as e:
            return JsonResponse({
                'status': 500,
                'message': f'获取用户信息失败：{str(e)}'
            }, status=500)
    else:
        return JsonResponse({
            'status': 405,
            'message': '仅支持GET请求'
        }, status=405)

@csrf_exempt
def wechat_user_update(request):
    """
    更新微信用户信息接口
    需要先登录获取token
    """
    if request.method == 'POST':
        try:
            # 获取token
            token = request.headers.get('Authorization')
            if not token:
                return JsonResponse({
                    'status': 401,
                    'message': '缺少token'
                }, status=401)
            
            # 解析请求数据
            data = json.loads(request.body)
            
            # 获取用户信息
            try:
                user = WechatUser.objects.get(token=token)
            except WechatUser.DoesNotExist:
                return JsonResponse({
                    'status': 401,
                    'message': '无效的token'
                }, status=401)
            
            # 检查token是否过期
            if not user.is_token_valid():
                return JsonResponse({
                    'status': 401,
                    'message': 'token已过期'
                }, status=401)
            
            # 更新用户信息
            if 'nickname' in data:
                user.nickname = data['nickname']
            if 'avatar' in data:
                user.avatar = data['avatar']
            if 'gender' in data:
                user.gender = data['gender']
            if 'country' in data:
                user.country = data['country']
            if 'province' in data:
                user.province = data['province']
            if 'city' in data:
                user.city = data['city']
            
            # 保存更新
            user.save()
            
            return JsonResponse({
                'status': 200,
                'message': '更新成功',
                'data': {
                    'nickname': user.nickname,
                    'avatar': user.avatar,
                    'gender': user.gender,
                    'country': user.country,
                    'province': user.province,
                    'city': user.city
                }
            })
            
        except json.JSONDecodeError:
            return JsonResponse({
                'status': 400,
                'message': '无效的JSON数据'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'status': 500,
                'message': f'更新失败：{str(e)}'
            }, status=500)
    else:
        return JsonResponse({
            'status': 405,
            'message': '仅支持POST请求'
        }, status=405) 